package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.dto.PluginCreateDto;
import com.cavy.platform.server.repository.PluginRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证插件名称不能重复
 */
public class NotRepeatPluginNameValidator implements ConstraintValidator<NotRepeatPluginName, PluginCreateDto> {
    private PluginRepository bean;
    @Override
    public void initialize(NotRepeatPluginName notRepeatPluginName) {
        bean = BeansProvider.getBean(PluginRepository.class);
    }

    @Override
    public boolean isValid(PluginCreateDto dto, ConstraintValidatorContext context) {
        assert bean != null;
        long count = bean.countByName(dto.getName(), dto.getVersion());
        if (count == 0) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("已经存在该名称(版本)的插件").addPropertyNode("name").addConstraintViolation();
        return false;
    }
}
